import pathlib
import time
import re
import typing
import os
import yaml
import ctypes
import psutil
import subprocess
import requests
import winsound
import datetime
import rich
from selenium.webdriver.edge.webdriver import WebDriver
from selenium.webdriver.edge.service import Service
from selenium.webdriver.edge.options import Options
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.common.exceptions import *
from rich import print





def print_with_time(*args, **kwargs):
    """在输出内容前添加当前时间戳，使用rich.print进行格式化输出
    
    功能：在所有输出内容前自动添加当前本地时间，时间格式为YYYY-MM-DD HH:MM:SS
    时间会以蓝色加粗样式显示，其余内容保持rich的默认格式化特性
    
    Args:
        *args: 任意数量的位置参数，将被原样传递给rich.print
        **kwargs: 任意关键字参数，将被原样传递给rich.print
    
    Example:
        >>> print_with_time("系统启动完成")
        [bold blue][2025-08-07 16:45:30][/bold blue] 系统启动完成
        
        >>> print_with_time("操作结果：", "[green]成功[/green]")
        [bold blue][2025-08-07 16:46:10][/bold blue] 操作结果：[green]成功[/green]
    """
    # 获取当前时间并格式化为字符串
    current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    # 拼接时间前缀与输出内容并打印
    rich.print(f"[bold blue][{current_time}][/bold blue]", *args, **kwargs)






def On_InputPage_InputMaterial(driver:WebDriver,AttributeName:str,AttributeValue:typing.Union[str,list],Delay:float=0.5):
    

    # 添加面料成分
    try:
        xpath_value = f"//button/span[text()='添加材质成分']"
        element = WebDriverWait(driver=driver,timeout=10).until(expected_conditions.presence_of_element_located(locator=(By.XPATH,xpath_value)))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        
        # 点击操作
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
        
        # 验证点击
        try:
            actions_element_xpath = "//input[@placeholder='请选择材质']"
            WebDriverWait(driver=driver,timeout=5).until(expected_conditions.presence_of_element_located(locator=(By.XPATH,actions_element_xpath)))
        except TimeoutException:
            print_with_time("提示 : 点击之后没有等到需要定位的元素!")
            return 
        
    except TimeoutException:
            print_with_time("提示 : 没有找到 [添加材质成分] 按钮!")
            return
            
    # 打开填写面料的输入框
    try:
        xpath_value = f"//input[@placeholder='请选择材质' and @value='']"
        element = WebDriverWait(driver=driver,timeout=10).until(expected_conditions.presence_of_element_located(locator=(By.XPATH,xpath_value)))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        
        # 点击操作
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
        
        # 验证点击
        try:
            actions_element_xpath = "//div[@class='options-search']//input"
            WebDriverWait(driver=driver,timeout=5).until(expected_conditions.presence_of_element_located(locator=(By.XPATH,actions_element_xpath)))
        except TimeoutException:
            print_with_time("提示 : 点击之后没有等到需要定位的元素!")
            return 
    except TimeoutException:
        print_with_time("提示 : 没有找到可以打开 [输入框] 的元素!")
        return

    # 输入面料材质成分
    try:
        xpath_value = f"//div[@class='options-search']//input"
        element = WebDriverWait(driver=driver,timeout=10).until(expected_conditions.presence_of_element_located(locator=(By.XPATH,xpath_value)))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        
        # 输入操作
        element.send_keys(AttributeValue[0])
        
        # 验证输入
        try:
            actions_element_xpath = f"//div[@class='options-item']//div[text()='{AttributeValue[0]}']"
            WebDriverWait(driver=driver,timeout=5).until(expected_conditions.presence_of_element_located(locator=(By.XPATH,actions_element_xpath)))
        except TimeoutException:
            print_with_time("提示 : 点击之后没有等到需要定位的元素!")
            return 
    except TimeoutException:
        print_with_time("提示 : 没有找到可以打开 [输入框] 的元素!")
        return

    # 选择面料材质成分
    try:
        xpath_value = f"//div[@class='options-item']//div[text()='{AttributeValue[0]}']"
        element = WebDriverWait(driver=driver,timeout=10).until(expected_conditions.presence_of_element_located(locator=(By.XPATH,xpath_value)))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        
        # 点击操作
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)

        # 验证点击
        try:
            actions_element_xpath = f"//em[@title='{AttributeValue[0]}' and text()='{AttributeValue[0]}']"
            WebDriverWait(driver=driver,timeout=5).until(expected_conditions.presence_of_element_located(locator=(By.XPATH,actions_element_xpath)))
        except TimeoutException:
            print_with_time("提示 : 点击之后没有等到需要定位的元素!")
            return 
    except TimeoutException:
        print_with_time("提示 : 没有找到可以打开 [输入框] 的元素!")
        return

    # 输入面料材质成分百分比
    try:
        xpath_value = f"//input[@placeholder='输入含量' and @value]"
        element = WebDriverWait(driver=driver,timeout=10).until(expected_conditions.presence_of_element_located(locator=(By.XPATH,xpath_value)))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        
        # 输入操作
        element.send_keys(AttributeValue[1])
        
        # 验证输入
        if element.get_attribute("value") == str(AttributeValue[1]):
            print_with_time("提示 : 成分含量输入成功!")
        else:
            print_with_time("提示 : 成分含量输入失败!")
            return 
        
    except TimeoutException:
        print_with_time("提示 : 没有找到可以打开 [输入框] 的元素!")
        return

    return
    








def On_InputPage_InputBasicParameters(driver:WebDriver,AttributeName:str,AttributeValue:typing.Union[str,list],Delay:float=0.5):
    """填写基础参数

    Args:
        driver (WebDriver): driver 实例
        wait (WebDriverWait): WebDriverWait 实例
        actions (ActionChains): ActionChains 实例
    """
    if AttributeName == "面料材质" or AttributeName == "面料成分" or AttributeName == "材质成分":
        On_InputPage_InputMaterial(driver=driver,AttributeName=AttributeName,AttributeValue=AttributeValue)
        return
    
    
    try:
        element = driver.find_element(by=By.XPATH,value=f"//*[text()='点击展开']")
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
    except NoSuchElementException:
        pass

    
    # 触发外部的 Input 元素,使其显式显式 输入框
    try:
        element = WebDriverWait(driver=driver,timeout=10).until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[contains(@class,'default-items-item') and .//span[text()='{AttributeName}']]//input")))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
        
        # 对 [内部输入框] 进行赋值输入
        try:
            element = WebDriverWait(driver=driver,timeout=10).until(expected_conditions.visibility_of_element_located((By.XPATH,f"//div[@class='sell-o-select-options']//input")))
            element.send_keys(AttributeValue)
            time.sleep(Delay)
            # 等待 [内部输入框] 的输入完毕,并且确认内容
            try:
                WebDriverWait(driver=driver,timeout=10).until(expected_conditions.text_to_be_present_in_element_value((By.XPATH,f"//div[@class='sell-o-select-options']//input"),text_=AttributeValue))

                try:
                    element = WebDriverWait(driver=driver,timeout=10).until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[@title='{AttributeValue}']/*/div[text()='{AttributeValue}']")))
                    element.click() 
                except (ElementClickInterceptedException,ElementNotInteractableException):
                    driver.execute_script("arguments[0].click();",element)

                
            except TimeoutException:
                print_with_time("提示 : 输入属性值失败!请检查!")

            
        except TimeoutException:
            print_with_time("提示 : 没有等到可以输入的内部输入框!")
        
    except TimeoutException:
        print_with_time("提示 : 没有找到 {AttributeName} 对应的外部触发输入框的元素!")